/**
 * @link https://www.kancloud.cn/cleverstone/ymb2
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */
-function (global, top) {
    "use strict";
    // 首页
    global.ym2App
        .factory("G2", function () {
            return global.G2 || {};
        })
        .controller("ym2.ctrl.home.index", ["$scope", "$http", "toastr", "ym2", "ymSpinner", "layui", "G2", "lodash", function ($scope, $http, toastr, ym2, ymSpinner, layui, G2, lodash) {
            /******************* CONSTANT ********************/
            //常量
            const TOP_TOASTR = top.toastr;
            const TOP_LAYER = top.layer;
            const LAYER = layui.layer;
            // const APP_THEME_COLOR = ym2.getAppThemeColor();
            const APP_THEME_COLOR = "#008cff";

            /******************* CONSTRUCT ********************/
            //初始化
            $scope.initScope = function () {
                $scope.userIncrItem = '1';
                $scope.orderIncrItem = '1';

                $scope.tlog = [];
                $scope.appLog = [];

                $scope.tlogIsEmpty = false;
                $scope.appLogIsEmpty = false;

                $scope.totalUserCount = '--';
                $scope.normalUserCount = '--';
                $scope.abnormalUserCount = '--';
                $scope.newUserCount = '--';

                $scope.isDisplayCapital = false;
                $scope.totalAmount = '0.00';
                $scope.totalAmount_unit = '';
                $scope.todayAmount = '0.00';
                $scope.todayAmount_unit = '';

                $scope.orderCount = '--';
                $scope.orderCount_unit = '';
                $scope.orderWaitPayCount = '--';
                $scope.orderWaitPayCount_unit = '';
                $scope.orderWaitPostCount = '--';
                $scope.orderWaitPostCount_unit = '';
                $scope.orderWaitUseCount = '--';
                $scope.orderWaitUseCount_unit = '';

                $scope.aftermarketCount = '--';
                $scope.aftermarketCount_unit = '';
                $scope.aftermarketApplyingCount = '--';
                $scope.aftermarketApplyingCount_unit = '';
                $scope.aftermarketWaitReceiveCount = '--';
                $scope.aftermarketWaitReceiveCount_unit = '';

                $scope.userIncrStatistics();
                $scope.orderIncrStatistics();
                $scope.appDataStatistics();
                $scope.getTlogAndAppLog();
            }

            /******************* PRIVATE ********************/
            //用户日增统计
            $scope.userIncrStatistics = function () {
                $scope.userIncrStatisticsSpinnerShow = true;
                $scope.userIncrStatisticsIsEmpty = false;
                $http.get("/home/_user_incr_statistics?days=" + $scope.userIncrItem).then(function (result) {
                    $scope.userIncrStatisticsSpinnerShow = false;
                    var data = result.data;
                    if (data.length > 0) {
                        $scope.drawUserIncrGraph(data);
                    } else {
                        $scope.userIncrStatisticsIsEmpty = true;
                    }
                }, function (error) {
                    $scope.userIncrStatisticsSpinnerShow = false;
                    $scope.userIncrStatisticsIsEmpty = true;
                    TOP_TOASTR.error(error.data || "出错了！发起请求失败~");
                    global.console.error(error);
                });
            };
            $scope.drawUserIncrGraph = function (data) {
                //画用户日增统计图
                var chart = new G2.Chart({
                    container: 'G2-userIncrStatistics',
                    autoFit: true,
                    height: 300,
                    padding: 24,
                });

                chart
                    .data(data)
                    .encode('x', 'time')
                    .encode('y', 'count')
                    .axis('x', {
                        title: false,
                        labelFilter: function (datum, index, data) {
                            return index % 2;
                        },

                        line: true, // 是否显示轴线
                        lineLineWidth: 1, // 轴线描边宽度
                        lineStroke: '#777', // 轴线描边颜色
                        arrow: false, // 是否显示箭头
                        lineOpacity: 1, // 轴线整体透明度

                        grid: true, // 是否显示网格线
                        gridLineWidth: 1, // 网格线描边宽度
                        gridStroke: '#e6e6e6', // 网格线描边颜色
                        gridStrokeOpacity: 0.7, // 网格线描边透明度
                        gridLineDash: [5, 5], // 网格线描边虚线配置
                        gridOpacity: 0.8, // 网格线整体透明度
                    })
                    .axis('y', {
                        title: false,
                        labelFilter: function (datum, index, data) {
                            return lodash.isInteger(datum);
                        },

                        line: true, // 是否显示轴线
                        lineLineWidth: 1, // 轴线描边宽度
                        lineStroke: '#777', // 轴线描边颜色
                        arrow: false, // 是否显示箭头
                        lineOpacity: 1, // 轴线整体透明度

                        grid: true, // 是否显示网格线
                        gridLineWidth: 1, // 网格线描边宽度
                        gridStroke: '#e6e6e6', // 网格线描边颜色
                        gridStrokeOpacity: 0.7, // 网格线描边透明度
                        gridLineDash: [5, 5], // 网格线描边虚线配置
                        gridOpacity: 0.8, // 网格线整体透明度
                    });

                chart
                    .line()
                    .encode('shape', 'smooth')
                    .animate('enter', {type: 'pathIn'})
                    .style('stroke', APP_THEME_COLOR)
                    .tooltip({
                        items: [
                            {
                                name: '时间',
                                field: 'date',
                                color: '#abc',
                            },
                            {
                                name: '数量',
                                channel: 'y',
                                valueFormatter: function (d) {
                                    return d + '人';
                                },
                                color: '#def',
                            },
                        ],
                    })
                    .style('lineWidth', 3);

                chart
                    .point()
                    .encode('shape', 'hollow')
                    .encode('size', 2)
                    .style('stroke', APP_THEME_COLOR)
                    .tooltip(false);

                chart
                    .area()
                    .encode('shape', 'smooth')
                    .style('fill', 'l(270) 0:#ffffff 0.5:#7ec2f3 1:#1890ff')
                    .style('fillOpacity', 0.15)
                    .tooltip(false);

                chart.render();
            };

            //订单日增统计
            $scope.orderIncrStatistics = function () {
                $scope.orderIncrStatisticsSpinnerShow = true;
                $scope.orderIncrStatisticsIsEmpty = false;
                $http.get("/home/_order_incr_statistics?days=" + $scope.orderIncrItem).then(function (result) {
                    $scope.orderIncrStatisticsSpinnerShow = false;
                    var data = result.data;
                    if (data.length > 0) {
                        if ($scope.orderIncrItem.substring(0, 1) === "g") {
                            $scope.drawOrderIncrGraphByGroup(data);
                        } else {
                            $scope.drawOrderIncrGraph(data);
                        }

                    } else {
                        $scope.orderIncrStatisticsIsEmpty = true;
                    }
                }, function (error) {
                    $scope.orderIncrStatisticsSpinnerShow = false;
                    $scope.orderIncrStatisticsIsEmpty = true;
                    TOP_TOASTR.error(error.data || "出错了！发起请求失败~");
                    global.console.error(error);
                });
            };
            $scope.drawOrderIncrGraphByGroup = function (data) {
                //画订单日增统计图(分组)
                var chart = new G2.Chart({
                    container: 'G2-orderIncrStatistics',
                    autoFit: true,
                    height: 300,
                    padding: 24,
                });

                chart
                    .data(data)
                    .encode('x', function (d) {
                        return new Date(d.date);
                    })
                    .encode('y', 'count')
                    .axis('x', {
                        title: false,
                        labelFormatter: function (datum, index, data) {
                            var date = new Date(datum);
                            if ($scope.orderIncrItem === "g1") {
                                return date.getHours() + ':00';
                            } else {
                                var day = date.getDate();
                                return (date.getMonth() + 1) + '/' + (day < 10 ? '0' + day : day);
                            }
                        },

                        line: true, // 是否显示轴线
                        lineLineWidth: 1, // 轴线描边宽度
                        lineStroke: '#777', // 轴线描边颜色
                        arrow: false, // 是否显示箭头
                        lineOpacity: 1, // 轴线整体透明度

                        grid: true, // 是否显示网格线
                        gridLineWidth: 1, // 网格线描边宽度
                        gridStroke: '#e6e6e6', // 网格线描边颜色
                        gridStrokeOpacity: 0.7, // 网格线描边透明度
                        gridLineDash: [5, 5], // 网格线描边虚线配置
                        gridOpacity: 0.8, // 网格线整体透明度
                    })
                    .axis('y', {
                        title: false,
                        labelFilter: function (datum, index, data) {
                            return lodash.isInteger(datum);
                        },

                        line: true, // 是否显示轴线
                        lineLineWidth: 1, // 轴线描边宽度
                        lineStroke: '#777', // 轴线描边颜色
                        arrow: false, // 是否显示箭头
                        lineOpacity: 1, // 轴线整体透明度

                        grid: true, // 是否显示网格线
                        gridLineWidth: 1, // 网格线描边宽度
                        gridStroke: '#e6e6e6', // 网格线描边颜色
                        gridStrokeOpacity: 0.7, // 网格线描边透明度
                        gridLineDash: [5, 5], // 网格线描边虚线配置
                        gridOpacity: 0.8, // 网格线整体透明度
                    });

                chart
                    .point()
                    .encode('shape', 'circle')
                    .encode('size', 2)
                    .encode('color', 'order_status')
                    .encode('series', 'order_status')
                    .style('stroke', APP_THEME_COLOR)
                    .tooltip(false);

                chart
                    .line()
                    .encode('shape', 'smooth')
                    .encode('color', 'order_status')
                    .encode('series', 'order_status')
                    .animate('enter', {
                        type: 'pathIn'
                    })
                    .style('lineWidth', 3)
                    .tooltip({
                        title: 'date',
                        items: [
                            {
                                channel: 'y',
                                name: '数量',
                                valueFormatter: function (d) {
                                    return d + '单';
                                }
                            }
                        ],
                    });

                chart.render();
            };
            $scope.drawOrderIncrGraph = function (data) {
                //画订单日增统计图
                var chart = new G2.Chart({
                    container: 'G2-orderIncrStatistics',
                    autoFit: true,
                    height: 300,
                    padding: 24,
                });

                chart
                    .data(data)
                    .encode('x', function (d) {
                        return new Date(d.date);
                    })
                    .encode('y', 'count')
                    .axis('x', {
                        title: false,
                        labelFormatter: function (datum, index, data) {
                            var date = new Date(datum);
                            if ($scope.orderIncrItem === "1") {
                                return date.getHours() + ':00';
                            } else {
                                var day = date.getDate();
                                return (date.getMonth() + 1) + '/' + (day < 10 ? '0' + day : day);
                            }
                        },

                        line: true, // 是否显示轴线
                        lineLineWidth: 1, // 轴线描边宽度
                        lineStroke: '#777', // 轴线描边颜色
                        arrow: false, // 是否显示箭头
                        lineOpacity: 1, // 轴线整体透明度

                        grid: true, // 是否显示网格线
                        gridLineWidth: 1, // 网格线描边宽度
                        gridStroke: '#e6e6e6', // 网格线描边颜色
                        gridStrokeOpacity: 0.7, // 网格线描边透明度
                        gridLineDash: [5, 5], // 网格线描边虚线配置
                        gridOpacity: 0.8, // 网格线整体透明度
                    })
                    .axis('y', {
                        title: false,
                        labelFilter: function (datum, index, data) {
                            return lodash.isInteger(datum);
                        },

                        line: true, // 是否显示轴线
                        lineLineWidth: 1, // 轴线描边宽度
                        lineStroke: '#777', // 轴线描边颜色
                        arrow: false, // 是否显示箭头
                        lineOpacity: 1, // 轴线整体透明度

                        grid: true, // 是否显示网格线
                        gridLineWidth: 1, // 网格线描边宽度
                        gridStroke: '#e6e6e6', // 网格线描边颜色
                        gridStrokeOpacity: 0.7, // 网格线描边透明度
                        gridLineDash: [5, 5], // 网格线描边虚线配置
                        gridOpacity: 0.8, // 网格线整体透明度
                    });

                chart
                    .line()
                    .encode('shape', 'smooth')
                    .tooltip({
                        title: 'date',
                        items: [
                            {
                                channel: 'y',
                                name: '数量',
                                valueFormatter: function (d) {
                                    return d + '单';
                                }
                            }
                        ],
                    })
                    .animate('enter', {
                        type: 'pathIn'
                    })
                    .style('stroke', APP_THEME_COLOR)
                    .style('lineWidth', 3);

                chart
                    .point()
                    .encode('shape', 'hollowHexagon')
                    .encode('size', 2)
                    .style('stroke', APP_THEME_COLOR)
                    .tooltip(false);

                chart
                    .area()
                    .encode('shape', 'smooth')
                    .style('fill', 'l(270) 0:#ffffff 0.5:#7ec2f3 1:#1890ff')
                    .style('fillOpacity', 0.15)
                    .tooltip(false);

                chart.render();
            };

            // 获取数据统计数据
            $scope.appDataStatistics = function () {
                $scope.dataStatisticsSpinnerShow = true;
                $http.get('/home/index').then(function (result) {
                    $scope.dataStatisticsSpinnerShow = false;

                    var data = result.data;
                    $scope.totalUserCount = data.totalUserCount;
                    $scope.normalUserCount = data.normalUserCount;
                    $scope.abnormalUserCount = data.abnormalUserCount;
                    $scope.newUserCount = data.newUserCount;
                    var [totalAmount, unit1] = ym2.unit(data.totalAmount, true);
                    var [todayAmount, unit2] = ym2.unit(data.todayAmount, true);
                    $scope.totalAmount = totalAmount;
                    $scope.totalAmount_unit = unit1;
                    $scope.todayAmount = todayAmount;
                    $scope.todayAmount_unit = unit2;
                    var [orderCount, unit3] = ym2.unit(data.orderCount, true);
                    var [orderWaitPayCount, unit4] = ym2.unit(data.orderWaitPayCount, true);
                    var [orderWaitPostCount, unit5] = ym2.unit(data.orderWaitPostCount, true);
                    var [orderWaitUseCount, unit6] = ym2.unit(data.orderWaitUseCount, true);
                    $scope.orderCount = orderCount;
                    $scope.orderCount_unit = unit3;
                    $scope.orderWaitPayCount = orderWaitPayCount;
                    $scope.orderWaitPayCount_unit = unit4;
                    $scope.orderWaitPostCount = orderWaitPostCount;
                    $scope.orderWaitPostCount_unit = unit5;
                    $scope.orderWaitUseCount = orderWaitUseCount;
                    $scope.orderWaitUseCount_unit = unit6;
                    var [aftermarketCount, unit7] = ym2.unit(data.aftermarketCount, true);
                    var [aftermarketApplyingCount, unit8] = ym2.unit(data.aftermarketApplyingCount, true);
                    var [aftermarketWaitReceiveCount, unit9] = ym2.unit(data.aftermarketWaitReceiveCount, true);
                    $scope.aftermarketCount = aftermarketCount;
                    $scope.aftermarketCount_unit = unit7;
                    $scope.aftermarketApplyingCount = aftermarketApplyingCount;
                    $scope.aftermarketApplyingCount_unit = unit8;
                    $scope.aftermarketWaitReceiveCount = aftermarketWaitReceiveCount;
                    $scope.aftermarketWaitReceiveCount_unit = unit9;

                }, function (errors) {
                    $scope.dataStatisticsSpinnerShow = false;

                    TOP_TOASTR.error(errors.data || "出错了！发起请求失败~");
                    global.console.error(errors);
                });
            };

            // 获取操作记录和应用日志
            $scope.getTlogAndAppLog = function () {
                // 应用日志
                $scope.appLogSpinnerShow = true;
                $http.get('/home/_app_log').then(function (result) {
                    $scope.appLogSpinnerShow = false;

                    var data = result.data;
                    $scope.appLog = data.appLog || [];
                    $scope.appLog.forEach(function (value) {
                        value.created_at = (new Date(value.created_at)).toLocaleTimeString("zh-CN");
                    });

                    if (!$scope.appLog.length) {
                        $scope.appLogIsEmpty = true;
                    }
                }, function (errors) {
                    $scope.appLogSpinnerShow = false;

                    TOP_TOASTR.error(errors.data || "出错了！发起请求失败~");
                    global.console.error(errors);
                });
                // 操作日志
                $scope.tlogSpinnerShow = true;
                $http.get('/home/_t_log').then(function (result) {
                    $scope.tlogSpinnerShow = false;

                    var data = result.data;
                    $scope.tlog = data.tlog || [];
                    $scope.tlog.forEach(function (value) {
                        value.created_at = (new Date(value.created_at)).toLocaleTimeString("zh-CN");
                    });

                    if (!$scope.tlog.length) {
                        $scope.tlogIsEmpty = true;
                    }
                }, function (errors) {
                    $scope.tlogSpinnerShow = false;

                    TOP_TOASTR.error(errors.data || "出错了！发起请求失败~");
                    global.console.error(errors);
                });
            };

            /******************* METHOD ********************/
            var tipFn = layui.throttle(function (evt, content) {
                LAYER.tips(content, evt.target, {
                    tips: [4, "#fff"], time: 3500,
                });
            }, 200);
            //查看操作记录详情
            $scope.showTlogDetail = function (evt, data) {
                var content = `
<ul class="layui-font-black f13">
    <li class="text-truncate"><label class="text-label font-weight-normal w-40">账号</label>${data.admin ? data.admin.username : "系统机器人"}</li>
    <li class="text-truncate"><label class="text-label font-weight-normal w-40">权限</label><span class="ym2-text-code">${data.route}</span></li>
    <li class="text-truncate"><label class="text-label font-weight-normal w-40">种类</label>${data.category}</li>
    <li class="line-height12"><label class="text-label font-weight-normal w-40">描述</label><span class="line-height20">${data.message}</span></li>
    <li class="text-truncate"><label class="text-label font-weight-normal w-40">时间</label>${data.created_at}</li>
<ul>
`;
                tipFn(evt, content);
            };

            //查看应用日志详情
            $scope.showAppLogDetail = function (logID) {
                var flag = ymSpinner.show();
                $http.get("/home/_app_log_detail?id=" + logID).then(function (result) {
                    ymSpinner.hide(flag);
                    var data = result.data;
                    TOP_LAYER.open({
                        type: 1, // page 层类型
                        area: ["850px", "550px"], title: false, shade: 0.3, // 遮罩透明度
                        shadeClose: true, // 点击遮罩区域，关闭弹层
                        maxmin: false, // 允许全屏最小化
                        closeBtn: 0, anim: 0, // 0-6 的动画形式，-1 不开启
                        scrollbar: false, // 打开弹层时，是否允许浏览器出现滚动条。
                        content: `<textarea class="layui-textarea log-message-editor">${data}</textarea>`,
                    });
                }, function (error) {
                    ymSpinner.hide(flag);
                    TOP_TOASTR.error(error.data || "出错了！发起请求失败~");
                    global.console.error(error);
                });
            };

            //切换用户日增统计图
            $scope.selectUserIncrItem = function () {
                $scope.userIncrStatistics();
            };

            //切换订单日增统计图
            $scope.selectOrderIncrItem = function () {
                $scope.orderIncrStatistics();
            };

            //初始化
            $scope.initScope();
        }]);
}(window, top);